# -*- coding: utf-8 -*-
import sys
import logging
from lxml import etree
from xadmin.model import *
from xadmin.lib.base import *
from xadmin.lib.associations import Association

class PRPRODAssociation(Association):
    def get(self):
        c.prprodassociations = Session.query(CrPrAssociation).all()
        return render('/associations/prprod.mako')

    def getByProject(self, project):
        try:
            project = Session.query(Project).get(project)
            associations = Session.query(ProductRequirement).add_entity(PrProdAssociation).join('products_assoc').filter(ProductRequirement.project_id==project.id).all()
            c.prprodassociations = []
            for association in associations:
                c.prprodassociations.append(association[1])
            return render('/associations/prprod.mako')
        except:
            print "ERROR: ", sys.exc_info()[0]
            return ''

    def create(self, project, data):
        try:
            project = Session.query(Project).get(project)
            tree = etree.fromstring(data.encode())
            associations = tree.xpath('/associations/association')
            for association in associations:
                pr_id = association[0].xpath('id')[0].text
                prod_id = association[1].xpath('id')[0].text
                pr = Session.query(ProductRequirement).get(pr_id)
                prod = Session.query(Product).get(prod_id)
                res = self._exists(pr_id, prod_id)
                if not res:
                    assoc = PrProdAssociation()
                    assoc.products = prod
                    pr.products_assoc.append(assoc)
                    Session.save(assoc)
                    Session.commit()
                else:
                    assoc = res
            return assoc
        except:
            print "ERROR: ", sys.exc_info()[0]
            return None

    def delete(self):
        pass

    def _exists(self, pr_id, prod_id):
        try:
            assoc = Session.query(PrProdAssociation).filter_by(pr_id=pr_id, prod_id=prod_id).one()
            return assoc
        except:
            return None